import Cesium from '../Ces/Cesium';
import WeSurface from './WeSurface';

class WeSurfaceManager {
  // Member variables
  rectangle;
  _display;
  _dataProvider;
  extrudedHeight;
  _objects;
  _sectPositionX;
  _sectPositionZ;

  constructor(options) {
    this.rectangle = options.rectangle;
    this._display = options.display;
    this._dataProvider = options.dataProvider;

    const size = options.dataProvider.externalData.size;
    this.extrudedHeight = size ? size.depth : 0.0;
    this._objects = new Cesium.AssociativeArray();
    this._sectPositionX = 0.0;
    this._sectPositionZ = 0.0;
  }

  get sectPositionZ() {
    return this._sectPositionZ;
  }

  set sectPositionZ(value) {
    if (value >= 0.0 && value <= 1.0) {
      this._sectPositionZ = value;
      for (let i = 0; i < this._objects.length; i++) {
        const primitive = this._objects._array[i];
        primitive.sectPositionZ = value;
      }
    }
  }

  remove(instance) {
    if (!Cesium.defined(instance)) {
      return false;
    }
    const id = instance instanceof WeSurface ? instance.id : instance;

    const obj = this._objects.get(id);

    if (!Cesium.defined(obj)) {
      return false;
    }

    if (!this._objects.remove(id)) {
      return false;
    }

    obj.destroy();

    return true;
  }

  removeAll() {
    for (let i = 0; i < this._objects.length; i++) {
      this._objects._array[i].destroy();
    }
    this._objects.removeAll();
  }

  add(options) {
    const primitive = new WeSurface(options);

    this._objects.set(primitive.id, primitive);

    return primitive;
  }

  isDestroyed() {
    return false;
  }

  destroy() {
    this.removeAll();

    return Cesium.destroyObject(this);
  }

  update(frameState) {
    for (let i = 0; i < this._objects.length; i++) {
      const primitive = this._objects._array[i];

      primitive.update(frameState);
    }
  }
}

export default WeSurfaceManager;
